package com.longge;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Stack;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-05-02 02:46
 */
public class RemoveOuterParentheses {

    public String removeOuterParentheses(String S) {
        char[] chars = S.toCharArray();
        Stack<Character> stack = new Stack<>();
        HashSet<Integer> path = new HashSet<>();
        path.add(0);
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(') {
                stack.push('(');
            } else {
                stack.pop();
            }
            if (stack.isEmpty()) {
                path.add(i);
                path.add(i+1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (path.contains(i)) continue;
            sb.append(chars[i]);
        }
        return sb.toString();
    }
}
